let ofPlayApp = new Vue({
    el: '#ofPlayApp',
    data: {
        tags1: '',
        currentDate: '',
        load: true,
        loading: 0,
        loadings: 1,
        Episodes: [
            {episode: '', videoUrl: '', status: ''},
            {episode: '', videoUrl: '', status: ''},
            {episode: '', videoUrl: '', status: ''},
            {episode: '', videoUrl: '', status: ''},
            {episode: '', videoUrl: '', status: ''},
            {episode: '', videoUrl: '', status: ''}
        ],
        Episode: [
            {episode: '', videoUrl: '', status: ''},
            {episode: '', videoUrl: '', status: ''},
            {episode: '', videoUrl: '', status: ''},
            {episode: '', videoUrl: '', status: ''},
            {episode: '', videoUrl: '', status: ''},
            {episode: '', videoUrl: '', status: ''}
        ],
        CosSelectUrl: [],
        video: [], // 视频列表主页
        next: [],  // 下一页
        tags: [],  // 视频类型
        checkbox: [],  // 是否显示
        isVisible: true,  // 是否显示删除内容
        isMessage: false, // 是否显示消息
        message: '',  // 消息内容 // 消息内容
        movie: [], // 视频信息 视频编辑页面
        insert: {
            name: '',
            imageUrl: '',
            content: '',
            tags: '',
            episode: '',
        }
    }, // 插入视频信息
    methods: {
        // 获取video视频
        ofPlayApp: function (pageNum) {
            if (pageNum == null) {
                pageNum = 1;
            }
            $.ajax({
                url: '/web/collectionPlay/select',
                method: 'GET',
                data: {
                    pageNum: pageNum
                },
                success: function (e) {
                    console.log("videos{}", e);
                    ofPlayApp.load = false;
                    ofPlayApp.next = e;
                    ofPlayApp.video = e.list;
                    for (let i = 0; i < e.list.length; i++) {
                        console.log("videos{}", ofPlayApp.video[i].displayed);
                        if (ofPlayApp.video[i].displayed == 0) {
                            ofPlayApp.video[i].displayed = false;
                        } else {
                            ofPlayApp.video[i].displayed = true;
                        }

                    }


                }
            })
        },
        // 修改视频是否显示
        oncheckbox: function (e) {
            console.log("e{}", e);
            console.log("e{}", e.target.checked);
            console.log("e{}", e.target.value);
            $.ajax({
                url: '/web/collectionPlay/update/displayed',
                method: 'GET',
                data: {
                    id: e.target.value,
                    displayed: e.target.checked ? 1 : 0
                },
                success: function (res) {
                    console.log("res{}", res);
                    if (res.code == OK) {
                        ofPlayApp.onmessage("状态修改成功");
                        console.log("状态成功修改");
                    }
                },
                error: function (e) {
                    console.log("状态修改失败");

                }
            })

        },
        // 收回删除内容
        oncollapse: function (e) {
            ofPlayApp.isVisible = false;
        },
        // 展开删除内容
        oncollapse1: function (e) {
            ofPlayApp.isVisible = true;
        }
        ,
        // 删除视频
        onDeleteById: function (e) {
            console.log("e{}", e);
            let arr = this.video;
            let index = arr.findIndex(item => item.id === e);
            console.log("index{}", index);
            $.ajax({
                url: '/web/collectionPlay/deleteById',
                method: 'GET',
                data: {
                    id: e,
                },
                success: function (res) {
                    console.log("res{}", res);
                    if (res.code == OK) {
                        arr.splice(index, 1);
                        ofPlayApp.video = arr;
                        ofPlayApp.isVisible = false;
                        ofPlayApp.onmessage("删除成功");
                    }
                },
                error: function (e) {
                    console.log("删除失败");
                    ofPlayApp.onmessage("删除失败");
                }

            })
        }
        ,
        // 提示框
        onmessage: function (message) {
            ofPlayApp.message = message;
            ofPlayApp.isMessage = true;
            setTimeout(function () {
                ofPlayApp.isMessage = false;
            }, 2000);
        },
        // 通过ID获取视频 进行修改
        handleInput: function (e) {
            var value = null;
            if (e) {
                value = e.target.value;
            }

            if (value === '' || value === null) {
                value = this.movie.id;
            }
            setTimeout(() => {
                console.log('Input changed:', value);
                $.ajax({
                    url: '/web/collectionPlay/selectById',
                    method: 'GET',
                    data: {
                        id: value,
                    },
                    success: function (e) {
                        if (e.code == OK) {
                            ofPlayApp.load = false;
                            console.log("videos{}", e.data);
                            ofPlayApp.movie = e.data;
                        }
                    }
                })
            }, 2000);

        },
        // 获取视频类型
        onTags: function () {
            $.ajax({
                url: '/web/collectionPlayTag/list',
                method: 'GET',
                success: function (res) {
                    console.log("res{}", res);
                    ofPlayApp.tags = res;
                },
                error: function (e) {
                    console.log("获取视频类型信息失败");
                }
            })

        },

        // 获取视频信息// 插入新数据
        insertSubmit: function (e) {
            // 在这里处理提交逻辑
            this.insert.gmtCreate = new Date().getTime();
            this.insert.displayed = 0;
            console.log('提交的数据insert数据:', this.insert);
            let data = this.insert;

            if (data.name == null) {
                ofPlayApp.onmessage("请输入视频标题");
                return;
            } else if (data.imageUrl == null) {
                ofPlayApp.onmessage("请输入视频封面地址");
                return;
            } else if (data.tags == null) {
                ofPlayApp.onmessage("请选择视频标签");
                return;
            }
            this.loading = 1;
            $.ajax({
                url: '/web/collectionPlay/insert',
                method: 'GET',
                data: data,
                success: function (res) {
                    console.log("res{}", res);
                    if (res.code == OK) {
                        ofPlayApp.loading = 0;
                        ofPlayApp.onmessage("上传成功");
                        ofPlayApp.insert = {};
                        ofPlayApp.ofPlayApp();
                    }
                },
                error: function (e) {
                    console.log("上传失败{}", e);
                    ofPlayApp.onmessage("上传失败");
                }
            })
        },

        // 剧集Url插入
        addUrlSubmit: function (e) {
            this.loading = 1;
            console.log(this.Episode);
            let data = this.Episode.map(item => {
                return {
                    ...item,           // 展开原对象的所有属性（episode, videoUrl, status 等）
                    videoId: this.movie.id  // 添加 videoId 字段
                };
            });
            console.log("处理后的数据（带 videoId）:", data);
            $.ajax({
                url: '/web/collectionPlayUrl/insert',
                method: 'POST',                    // ✅ 改为 POST
                contentType: 'application/json',   // ✅ 告诉后端是 JSON
                data: JSON.stringify(data),        // ✅ 序列化为 JSON 字符串
                success: function (res) {
                    console.log("提交成功:", res);
                    if (res.code == OK) {
                        ofPlayApp.Episode = [];
                        ofPlayApp.Episode = ofPlayApp.Episodes;
                        ofPlayApp.loading = 0;
                        ofPlayApp.handleInput(0);
                        ofPlayApp.onmessage("上传成功");
                    }
                    // 处理成功响应
                },
                error: function (xhr, status, error) {
                    ofPlayApp.loading = 0;
                    ofPlayApp.onmessage("提交失败");
                    console.log("提交失败:", error);
                    console.log("响应内容:", xhr.responseText);
                }
            });
        },
        // 自动化插入
        addUrlAptematicSubmit: function (e) {
            this.loading = 1;
            console.log(this.CosSelectUrl);
            let data = this.CosSelectUrl.map(item => {
                return {
                    ...item,
                    videoUrl:item.cdnUrl,
                    videoId: this.movie.id  // 添加 videoId 字段
                };
            });
            console.log("处理后的数据（带 videoId）:", data);
            $.ajax({
                url: '/web/collectionPlayUrl/insert',
                method: 'POST',                    // ✅ 改为 POST
                contentType: 'application/json',   // ✅ 告诉后端是 JSON
                data: JSON.stringify(data),        // ✅ 序列化为 JSON 字符串
                success: function (res) {
                    console.log("提交成功:", res);
                    if (res.code == OK) {
                        ofPlayApp.CosSelectUrl=[];
                        ofPlayApp.movie = [];
                        ofPlayApp.loading = 0;
                        ofPlayApp.onmessage("上传成功");
                    }
                    // 处理成功响应
                },
                error: function (xhr, status, error) {
                    ofPlayApp.loading = 0;
                    ofPlayApp.onmessage("提交失败");
                    console.log("提交失败:", error);
                    console.log("响应内容:", xhr.responseText);
                }
            });
        },
        handleUrlInput: function (e) {
            this.loadings = 1;
            var value = this.movie.name;
            const CosSelectUrls = '中文/ofPlay/' + value;
            console.log('CosSelectUrls:', CosSelectUrls);
            $.ajax({
                url: '/api/cos/list',
                method: 'GET',
                data: {
                    folderPath: CosSelectUrls,
                },
                success: function (e) {
                    console.log("成功", e.files);
                    for (let i = 0; i < e.files.length; i++) {
                        e.files[i].status = 1;
                        e.files[i].episode = i + 1;
                    }
                    ofPlayApp.CosSelectUrl = e.files;
                    ofPlayApp.loadings = 0 ;
                }
            })


        },
        // 获取当前时间
        formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        updateDate() {
            const now = new Date();
            this.currentDate = this.formatDate(now);
        }

    }, created: function () {
        // 初始化日期
        this.updateDate();
        // 每秒更新时间
        this.interval = setInterval(this.updateDate, 1000);

        this.onTags();
        this.ofPlayApp();
    },
    beforeDestroy() {
        // 清除定时器
        clearInterval(this.interval);
    }
})